<script setup lang="tsx">
import DialogUpload from '@/components/OrderPayment/UploadPayment/index.vue'
// import SupplementPayment from '@/components/OrderPayment/SupplementPayment/index.vue'
import BaseInfo from '@/views/Order/Order/components/Detail/BaseInfo/index.vue'
import Team from '@/views/Order/Order/components/Detail/Team/index.vue'
import Delivery from '@/views/Order/Order/components/Detail/Delivery/index.vue'
import Logistics from '@/views/Order/Order/components/Detail/Logistics/index.vue'
import FollowList from '@/views/Order/Order/components/Detail/FollowList/index.vue'
import ReceiptManagement from '@/views/Order/Order/components/Detail/ReceiptManagement/index.vue'
import InvoicingHistory from '@/views/Order/Order/components/Detail/InvoicingHistory/index.vue'
import FileCabinet from '@/views/Order/Order/components/Detail/FileCabinet/index.vue'
import WorkOrderRecord from '@/views/Order/Order/components/Detail/WorkOrderRecord/index.vue'
import ReturnsRefund from '@/views/Order/Order/components/Detail/ReturnsRefund/index.vue'
import RelatedProducts from '@/views/Order/Order/components/Detail/RelatedProducts/index.vue'
import OrderSended from '@/views/Order/Order/components/Detail/OrderSended/index.vue'

import ApprovalRecord from '@/views/Order/Order/components/Detail/ApprovalRecord/index.vue'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { useEnumeratePicker, encryptParam, decryptParam } from '@/utils'
import { getDetailApi, getEnumApi, getInventoryEnumApi, orderCancelApi } from '@/api/wholesalOrder'
import { orderDeleteApi, lockInventoryApi } from '@/api/order'
import { contractPreviewApi } from '@/api/order'
const { push, go } = useRouter()

// 移动端检测
import { useAppStore } from '@/store/modules/app'
const appStore = useAppStore()
const isMobile = computed(() => appStore.getMobile)
const { query } = useRoute()
const route = useRoute()
const { t } = useI18n()

const DialogUploadRef = ref<InstanceType<typeof DialogUpload>>()
// const SupplementPaymentRef = ref<InstanceType<typeof SupplementPayment>>()
const isLoading = ref(true) // 设置加载状态
const currentRow = ref<Record<string, any>>({})

// 跳转编辑
const action = () => {
  push({
    path: `/order/wholesal-order-management/edit`,
    query: { id: currentRow.value.id }
  })
}
//返回
const back = () => {
  push('/order/wholesal-order-management')
}

const activeName = ref(getInitialTab())

function getInitialTab(): string {
  // 优先从 URL 参数获取
  if (query.tab) {
    return query.tab as string
  }
  if (query.source) {
    return decodeURIComponent(query.source as string)
  }
  // 从 localStorage 获取上次选中的 tab
  const savedTab = localStorage.getItem('orderDetailActiveTab')
  if (savedTab) {
    return savedTab
  }
  // 默认选中第一个 tab
  return 'base_info'
}

// 监听 activeName 变化，更新 URL 和 localStorage
watch(activeName, (newValue) => {
  console.log('Tab changed to:', newValue)
  const currentQuery = { ...route.query, tab: newValue }
  push({ query: currentQuery })
  localStorage.setItem('orderDetailActiveTab', newValue)
})

// 根据 activeName 动态选择渲染的组件
const currentTabComponent = computed(() => {
  switch (activeName.value) {
    case 'base_info':
      return BaseInfo // 需要先定义 BaseInfo 组件
    case 'team':
      return Team // 需要先定义 Team 组件
    case 'delivery':
      return Delivery // 需要先定义 收货信息 组件
    case 'logistics':
      return Logistics // 需要先定义 物流信息 组件
    case 'follow_list':
      return FollowList // 需要先定义 物流信息 组件
    case 'work_order_record':
      return WorkOrderRecord // 需要先定义 WorkOrderRecord 组件
    case 'receipt_management':
      return ReceiptManagement // 需要先定义 ReceiptManagement 组件
    case 'invoicing_history':
      return InvoicingHistory // 需要先定义 InvoicingHistory 组件
    case 'returns_refund':
      return ReturnsRefund // 需要先定义 ReturnsRefund 组件
    case 'file_cabinet':
      return FileCabinet // 需要先定义 FileCabinet 组件
    case 'approval_record':
      return ApprovalRecord // 需要先定义 ApprovalRecord 组件
    case 'related_products':
      return RelatedProducts // 需要先定义 ApprovalRecord 组件
    case 'order_sended':
      return OrderSended // 需要先定义 OrderSended 组件
    default:
      return BaseInfo // 默认渲染 BaseInfo 组件
  }
})

interface Option {
  label: string
  value: string
}

const options = ref<Option[]>([{ label: t('order.previewContract'), value: 'preview' }]) // 定义为数组类型

// 处理下拉菜单的操作
const handleCommand = (command) => {
  console.log('执行的操作：', command)
  switch (command) {
    case 'newInvoice':
      push(
        `/order/invoice-management/add?order_id=${currentRow.value.id}&order_no=${currentRow?.value?.order_no}&customer_id=${currentRow?.value?.user_id}&cusname=${currentRow?.value?.user_name}&order_type=wholesal`
      )
      break
    case 'orderReturn':
      push({
        path: `/orderReturn-management/orderReturn/add`,
        query: { data: encodeURIComponent(JSON.stringify(currentRow.value)) }
      })
      break
    case 'preview':
      getFileUrl()
      break
    case 'copyOrder':
      const encryptedOrderId = encryptParam(currentRow.value.id)
      push({
        path: '/order/wholesal-order-management/add',
        query: { order: encryptedOrderId }
      })
      break
  }
}
const getFileUrl = async () => {
  try {
    let params = {
      order_id: Number(currentRow.value.id),
      order_type: 'wholesal'
    }
    let response = await contractPreviewApi(params)
    if (response.data.url) {
      pdfUrl.value = response.data.url
      previewVisible.value = true
    }
  } catch (error) {}
}
//获取枚举
const optionSet = ref<Record<string, any>>({})
const afterSalesStatusList = ref<any[]>([])
const getDropDownBoxInfo = async () => {
  Promise.all([getEnumApi({ field: 'all' }), getInventoryEnumApi({ field: 'all' })]).then(
    ([a, b]) => {
      optionSet.value = { ...a.data, ...b.data }
      afterSalesStatusList.value = a.data.aftersales_status || []
    }
  )
}

const initialize = async () => {
  const resp = await getDetailApi(query.id as string)
  currentRow.value = resp.data
  // isWholesal==true 表示是经销商订单
  currentRow.value.isWholesal = true
  currentRow.value.order_status = currentRow.value.status
  if (currentRow.value.pay_status === 3) {
    options.value.unshift({
      label: t('order.newReturnRefund'),
      value: 'orderReturn'
    })
  }
  if (currentRow.value.status === 100 && currentRow.value.pay_status === 3) {
    options.value.unshift({
      label: t('order.newInvoice'),
      value: 'newInvoice'
    })
  }
  options.value.push({
    label: t('order.copyOrder'),
    value: 'copyOrder'
  })
}
const countKey = ref(1)
const refresh = async () => {
  await initialize()
  countKey.value++
}
onMounted(async () => {
  Promise.all([initialize(), getDropDownBoxInfo()]).then(() => {
    isLoading.value = false // 数据加载完成后更新状态
    console.log('optionSet', optionSet.value)
  })
})
const checkCustomer = () => {
  push({ path: `/customer/customerList/detail`, query: { id: currentRow.value.user_id } })
}

const previewVisible = ref(false)
const pdfUrl = ref('')
// 关闭预览窗口
const handleClosePreview = () => {
  previewVisible.value = false
  pdfUrl.value = ''
  // 预览合同之后,需要更新文件柜
  if (activeName.value === 'file_cabinet') {
    countKey.value++
  }
}
const uploadPayment = (row: Record<string, any>, type: number) => {
  nextTick(() => {
    DialogUploadRef.value!.dialogVisible = true
    DialogUploadRef.value?.getBackShow(JSON.parse(JSON.stringify(row)), type, 'wholesal')
  })
}

// 方法
const handleJump = (type: string, row?: Record<string, any>) => {
  const path = ref<string>('') // 默认值为空字符串
  const query = reactive<{ [key: string]: string }>({}) // 默认值为空字符串
  switch (type) {
    case 'customer':
      path.value = `/customer/customerList/detail`
      query.id = row?.user_id
      query.source = `/order/order-management`
      break
    case 'lockInventory':
      handleLockInventory(row)
      break
    default:
      path.value = `/order/wholesal-order-management/${type}`
      query.id = row?.id
      break
  }

  push({ path: path.value, query })
}

const handleLockInventory = (row: Record<string, any> | undefined) => {
  console.log(row)
  ElMessageBox.confirm(t('common.message.operate'), t('common.tip'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(async () => {
      await lockInventoryApi({ id: row?.id })
      ElMessage.success(t('common.operateSucMsg'))
      await initialize()
    })
    .catch(() => {})
}
const handleCancelOrder = (row: Record<string, any>) => {
  ElMessageBox.confirm(t('common.message.cancel'), t('common.tip'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(async () => {
      await orderCancelApi(row.id)
      ElMessage.success(t('common.operateSucMsg'))
      await initialize()
    })
    .catch(() => {})
}
/**
 * 删除订单
 * @param row
 */
const handleDeleteOrder = (row: Record<string, any>) => {
  ElMessageBox.confirm(t('common.message.delete'), t('common.tip'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(async () => {
      await orderDeleteApi(row.id)
      ElMessage.success(t('common.operateSucMsg'))
      push('/order/wholesal-order-management')
    })
    .catch(() => {})
}
</script>

<template>
  <ContentDetailWrap :title="t('customer.detail')">
    <template #header v-if="!isLoading">
      <div class="header flex justify-between items-center" :class="{ '!block': isMobile }">
        <div class="header-left flex flex-start items-center">
          <div class="right" :class="{ 'flex justify-between items-center': isMobile }"
            ><div class="top">
              <p :style="{ fontWeight: 'bold', color: 'black' }"> {{ currentRow?.order_no }} </p>
            </div>
            <div class="bottom">
              <el-tag
                class="!bg-[var(--el-color-info-light-9)] !border-none !font-600"
                :class="{
                  '!text-[#67c23a]': currentRow.status === 100,
                  '!text-[#c8c9cc]': currentRow.status === 70,
                  '!text-[#20B2AA]': currentRow.status === 50,
                  '!text-[#9370DB]': currentRow.status === 40,
                  '!text-[#1E90FF]': currentRow.status === 30,
                  '!text-[#32CD32]': currentRow.status === 21,
                  '!text-[#FFD700]': currentRow.status === 20,
                  '!text-[#FFA500]': currentRow.status === 10
                }"
              >
                {{ useEnumeratePicker(optionSet.status, currentRow.status) }}
              </el-tag>
              <el-tag
                v-if="currentRow?.aftersales_status"
                class="!bg-[var(--el-color-info-light-9)] !border-none !font-600 !ml-2"
                :class="{
                  '!text-[#FFA500]': currentRow?.aftersales_status === 1, // 退货中
                  '!text-[#67c23a]': currentRow?.aftersales_status === 4, // 已退货
                  '!text-[#1E90FF]': currentRow?.aftersales_status === 8, // 退款中
                  '!text-[#9370DB]': currentRow?.aftersales_status === 16, // 已退款
                  '!text-[#FF6B6B]': currentRow?.aftersales_status === 32 // 已退货 已退款
                }"
              >
                {{ useEnumeratePicker(afterSalesStatusList, currentRow.aftersales_status) }}
              </el-tag>
            </div>
          </div>
        </div>
        <div class="header-right flex" :class="{ '!flex-wrap': isMobile }">
          <!-- 主要按钮区 -->
          <template v-if="currentRow.status !== 20">
            <BaseButton
              type="success"
              v-if="currentRow.pay_status === 3"
              v-hasPermi="['SupplementPaymentWholesal']"
              @click="uploadPayment(currentRow, 3)"
            >
              {{ t('order.supplementPayment') }}
            </BaseButton>

            <BaseButton
              type="primary"
              v-if="currentRow.status === 10 || currentRow.status === 21"
              @click="uploadPayment(currentRow, 1)"
            >
              {{ t('order.orderUpload') }}
            </BaseButton>
            <div class="button-group">
              <el-button
                type="primary"
                class="main-button"
                @click="handleCommand(options[0].value)"
              >
                {{ options[0].label }}
              </el-button>

              <el-dropdown
                @command="handleCommand"
                v-if="options.length > 1"
                placement="bottom-end"
              >
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-for="item in options.slice(1)"
                      :key="item.value"
                      :command="item.value"
                    >
                      {{ item.label }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
                <el-button type="primary" class="triangle-button">
                  <el-icon><ArrowDownBold /></el-icon>
                </el-button>
              </el-dropdown>
            </div>
            <el-button
              v-if="currentRow.show_entry"
              type="primary"
              @click="handleJump('wholesalInventoryTypeConversion', currentRow)"
              style="margin-left: 0"
            >
              {{ t('order.inventoryTypeConversion') }}
            </el-button>
            <el-button
              v-if="currentRow.review_node === 1"
              type="primary"
              @click="handleJump('lockInventory', currentRow)"
              style="margin-left: 0"
            >
              {{ t('order.lockInventory') }}
            </el-button>
            <el-button
              v-hasPermi="['WholesalOrderManagementEdit']"
              @click="handleJump('edit', currentRow)"
              v-if="
                (currentRow.status === 10 ||
                  currentRow.status === 30 ||
                  currentRow.status === 40) &&
                currentRow.review_node == 0
              "
              style="margin-left: 0"
            >
              {{ t('system.marketChannel.edit') }}
            </el-button>

            <el-button
              v-hasPermi="['WholesalOrderManagementCancel']"
              v-if="currentRow.status === 10"
              type="info"
              @click="handleCancelOrder(currentRow)"
              style="margin-left: 0"
            >
              {{ t('order.cancelOrder') }}
            </el-button>
            <el-button
              v-hasPermi="['WholesalOrderManagementDelete']"
              v-if="
                (currentRow.pay_status === 1 && currentRow.status === 10) ||
                currentRow.status === 70
              "
              type="danger"
              @click="handleDeleteOrder(currentRow)"
              style="margin-left: 0"
            >
              {{ t('order.deleteOrder') }}
            </el-button>
          </template>
          <el-button
            v-if="currentRow.status === 20"
            type="primary"
            @click="handleJump('audit', currentRow)"
            style="margin-left: 0"
          >
            {{ t('order.audit') }}
          </el-button>
          <BaseButton @click="back" style="margin-left: 0">
            {{ t('action.back') }}
          </BaseButton>
        </div>
      </div>
      <el-divider />
      <div class="nav flex flex-start items-center">
        <div class="flex flex-start items-center" @click="checkCustomer">
          <text>{{ t('wholesalOrder.wholesal') }}：</text>
          <el-link type="primary" class="!text-16px">{{ currentRow.user_name }}</el-link>
        </div>
        <text
          >{{ t('order.signatory') }}：{{
            useEnumeratePicker(optionSet.operator, currentRow.signatory)
          }}</text
        >
        <text>{{ t('order.signing_date') }}：{{ currentRow.signing_date }}</text>
      </div>
      <br />
      <div>
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane :label="t('order.baseInfo')" name="base_info" />
          <el-tab-pane :label="t('order.team')" name="team" />
          <el-tab-pane :label="t('order.followList')" name="follow_list" />
          <el-tab-pane :label="t('order.receiptManagement')" name="receipt_management" />
          <el-tab-pane :label="t('order.invoicingHistory')" name="invoicing_history" />
          <el-tab-pane :label="t('order.fileCabinet')" name="file_cabinet" />
          <el-tab-pane :label="t('order.workOrderRecord')" name="work_order_record" />
          <el-tab-pane :label="t('order.relatedProducts')" name="related_products" />
          <el-tab-pane :label="t('order.orderSended')" name="order_sended" />
          <el-tab-pane :label="t('order.approvalRecord')" name="approval_record" />
        </el-tabs>
        <!-- 动态加载对应的 tab 内容 -->
        <component
          v-if="!isLoading"
          :is="currentTabComponent"
          :key="countKey"
          :current-row="currentRow"
          :operator-options="optionSet"
          @refresh="refresh"
        />
      </div>
    </template>
  </ContentDetailWrap>
  <el-dialog
    v-model="previewVisible"
    :title="t('order.contract')"
    width="80%"
    height="92%"
    :before-close="handleClosePreview"
  >
    <iframe :src="pdfUrl" style="width: 100%; height: 80vh" frameborder="0"></iframe>
  </el-dialog>
  <!--      上传支付审核弹框-->
  <DialogUpload ref="DialogUploadRef" @refresh="initialize" />
</template>

<style lang="less" scoped>
// :deep(.el-upload-list__item .el-icon--close:hover) {
//   color: transparent !important;
//   opacity: 0 !important;
//   visibility: hidden;
// }

// :deep(.el-upload-list__item:hover .el-icon--close) {
//   display: none;
// }

// :deep(.el-upload-list__item.is-success:focus:not(:hover)) {
//   display: none !important;
// }

.header-right {
  display: flex;
  align-items: center;
  gap: 10px; /* 增加间距，使按钮不会挤在一起 */
}

.header-left .left {
  flex-direction: column;
  justify-content: space-around;
  margin-right: 10px;
}

.header-left .right .bottom span {
  margin-right: 10px;
}

.nav {
  gap: 50px;
}

.button-group {
  display: flex;
  align-items: center;
  gap: 0; /* 确保按钮组不额外增加间距 */
}

/* 主按钮样式 */
.main-button {
  margin-right: -1px; /* 让按钮无间隙连接 */
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

/* 下拉三角按钮 */
.triangle-button {
  display: flex;
  padding: 0 12px;
  border-bottom-left-radius: 0;
  border-top-left-radius: 0;
  align-items: center;
  justify-content: center;
}
</style>
